package com.example.child_protection.service.base;


import com.example.child_protection.dto.base.BaseRequestDTO;
import com.example.child_protection.dto.base.BaseResponseDTO;
import com.example.child_protection.enums.ResponseCodeEnums;
import com.example.child_protection.exception.MyBizException;
import com.example.child_protection.util.InstantiateUtils;
import com.example.child_protection.util.SystemCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

public abstract class MyServiceExecutor<REQUEST extends BaseRequestDTO, RESPONSE extends BaseResponseDTO> extends ServiceExecutor<REQUEST, RESPONSE> {
	private final Logger logger = LoggerFactory.getLogger( this.getClass() );

	@Override
	protected RESPONSE process( REQUEST requestDTO ) throws Exception {
		Class<RESPONSE> responseClass = Reflections.getClassGenricType( this.getClass(), 1 );
		RESPONSE responseDTO = InstantiateUtils.instantiate( responseClass );
		try {
			return this.myprocess( requestDTO );
		} catch ( DuplicateKeyException e ) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			this.logger.error( SystemCode.EXCEPTION, "process", e );
			responseDTO.setSuccess( true ).setExecuted( false ).setResponseCode( ResponseCodeEnums.DATABASE_EXCEPTION ).setMessage( "数据重复" );
			return responseDTO;
		} catch ( DataIntegrityViolationException e ) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			this.logger.error( SystemCode.EXCEPTION, "process", e );
			responseDTO.setSuccess( true ).setExecuted( false ).setResponseCode( ResponseCodeEnums.DATABASE_EXCEPTION ).setMessage( "数据库操作异常" );
			return responseDTO;
		} catch ( MyBizException e ) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			this.logger.error( SystemCode.EXCEPTION, "process", e );
			responseDTO.setSuccess( true ).setExecuted( false ).setResponseCode( ResponseCodeEnums.FAILED ).setMessage( e.getMessage() );
			return responseDTO;
		}catch(Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			throw e;
		}
	}

	protected abstract RESPONSE myprocess( REQUEST requestDTO ) throws Exception;

}
